<?php
/*
 * @Author       : ZengHao
 * @Date         : 2024-01-08 19:46:44
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-01-25 15:21:23
 * @FilePath     : \inc\action\action-post.php
 * @Description  : 
 * Copyright 2024 www.exehub.com, All Rights Reserved. 
 * 2024-01-08 19:46:44
 */

// ----  文章点赞功能 ----- //
//  增加发布文章时，向文章数据自定义字段
function add_post_like_field()
{
    add_post_meta('post', 'like', '0', true);
}
add_action('publish_post', 'add_post_like_field');

// 设置 like
add_action('wp_ajax_nopriv_set_post_like', 'el_set_post_like');
add_action('wp_ajax_set_post_like', 'el_set_post_like');
function el_set_post_like()
{
    global $wpdb, $post;
    $pid = $_POST["pid"];
    $action = $_POST["action"];
    // 用户ID，判断用户是否重复点赞
    $uid = is_user_logged_in() ? get_current_user_id() : 'anonymous';
    // 获取存储已经点赞的文章ID列表的cookie
    $like_posts_cookie = isset($_COOKIE['liked_posts']) ? $_COOKIE['liked_posts'] : '';
    // 将cookie转换为数组
    $liked_posts = explode(',', $like_posts_cookie);
    $likes = 0;
    // 检查用户是否已经点赞了
    if (!in_array($pid, $liked_posts)) {
        // 用户未点赞，处理点赞逻辑
        $likes = get_post_meta($pid, 'like', true);
        if (!$likes) {
            $likes = 0;
        }
        $likes++;
        update_post_meta($pid, 'like', $likes);
        // 记录用户已经点赞的文章ID到cookie
        $liked_posts[] = $pid;
        $like_posts_cookie = implode(',', $liked_posts);
        $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
        $expire = time() + 3600 * 24 * 30;
        setcookie('liked_posts', $like_posts_cookie, $expire, '/', $domain, false);
        wp_send_json_success(json_encode(
            array(
                'likes' => $likes,
                'pid' => $pid,
                'isliked' => false,
                'msg' => '感谢您的点赞'
            )
        ));
    } else {
        wp_send_json_success(json_encode(
            array(
                'likes' => -1,
                'pid' => $pid,
                'isliked' => true,
                'msg' => '您已经点过赞了'
            )
        ));
    }

    wp_die();
    do_action('posts_likes_record', $pid, $likes);
    die;
}


function get_post_likes($post = null)
{
    $post_id = $post->ID;
    $likes = ECache::get('post_likes' . $post_id);
    if (false === $likes) {
        $likes = get_post_meta($post_id, 'like', true);
        if (!$likes) {
            $likes = 0;
        }
        ECache::set('post_likes' . $post_id, EL_CACHE, DAY_IN_SECONDS);
    }
    return $likes;
}

add_action('wp_ajax_nopriv_get_post_like', 'el_get_post_like');
add_action('wp_ajax_get_post_like', 'el_get_post_like');
// 获取文章点赞数据
function el_get_post_like()
{
    $post_id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
    $likes = ECache::get('post_likes' . $post_id);
    if (false === $likes) {
        $likes = get_post_meta($post_id, 'like', true);
        if (!$likes) {
            $likes = 0;
        }
        ECache::set('post_likes' . $post_id, EL_CACHE, DAY_IN_SECONDS);
    }
    // 获取存储已经点赞的文章ID列表的cookie
    $like_posts_cookie = isset($_COOKIE['liked_posts']) ? $_COOKIE['liked_posts'] : '';
    // 将cookie转换为数组
    $liked_posts = explode(',', $like_posts_cookie);
    // 检查用户是否已经点赞了
    if (!in_array($post_id, $liked_posts)) {
        wp_send_json_success(json_encode(
            array(
                'likes' => $likes,
                'pid' => $post_id,
                'isliked' => false,
                'msg' => '感谢您的点赞'
            )
        ));
    } else {
        wp_send_json_success(json_encode(
            array(
                'likes' => $likes,
                'pid' => $post_id,
                'isliked' => true,
                'msg' => '感谢您的点赞'
            )
        ));
    }
}


// ----  文章收藏功能 ----- //

/**
 * @func: 
 * @description: 增加 自定义文章字段-收藏-favorite
 * @return {*}
 * @example: 
 */
function add_post_favorite_field()
{
    add_post_meta('post', 'favorite', '0', true);
}
add_action('publish_post', 'add_post_favorite_field');

// 设置 like
add_action('wp_ajax_nopriv_set_post_favorite', 'el_set_post_favorite');
add_action('wp_ajax_set_post_favorite', 'el_set_post_favorite');
function el_set_post_favorite()
{
    global $wpdb, $post;
    $pid = $_POST["pid"];
    $action = $_POST["action"];
    // 用户ID，判断用户是否重复点赞
    $uid = is_user_logged_in() ? get_current_user_id() : 'anonymous';
    // 获取存储已经点赞的文章ID列表的cookie
    $favorite_posts_cookie = isset($_COOKIE['favorited_posts']) ? $_COOKIE['favorited_posts'] : '';
    // 将cookie转换为数组
    $favorited_posts = explode(',', $favorite_posts_cookie);
    $favorites = 0;
    // 检查用户是否已经点赞了
    if (!in_array($pid, $favorited_posts)) {
        // 用户未点赞，处理点赞逻辑
        $favorites = get_post_meta($pid, 'favorite', true);
        if (!$favorites) {
            $favorites = 0;
        }
        $favorites++;
        update_post_meta($pid, 'favorite', $favorites);
        // 记录用户已经点赞的文章ID到cookie
        $favorited_posts[] = $pid;
        $favorite_posts_cookie = implode(',', $favorited_posts);
        $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
        $expire = time() + 3600 * 24 * 30;
        setcookie('favorited_posts', $favorite_posts_cookie, $expire, '/', $domain, false);
        wp_send_json_success(json_encode(
            array(
                'favorite' => $favorites,
                'pid' => $pid,
                'isfavorited' => false,
                'msg' => '感谢您的收藏'
            )
        ));
    } else {
        wp_send_json_success(json_encode(
            array(
                'favorites' => -1,
                'pid' => $pid,
                'isfavorited' => true,
                'msg' => '您已经收藏过了'
            )
        ));
    }

    wp_die();
    do_action('posts_favorite_record', $pid, $favorites);
    die;
}


function get_post_favorites($post = null)
{
    $post_id = $post->ID;
    $likes = ECache::get('post_favorites' . $post_id);
    if (false === $likes) {
        $likes = get_post_meta($post_id, 'favorite', true);
        if (!$likes) {
            $likes = 0;
        }
        ECache::set('post_favorites' . $post_id, EL_CACHE, DAY_IN_SECONDS);
    }
    return $likes;
}

add_action('wp_ajax_nopriv_get_post_favorite', 'el_get_post_favorite');
add_action('wp_ajax_get_post_favorite', 'el_get_post_favorite');
// 获取文章点赞数据
function el_get_post_favorite()
{
    $post_id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
    $favorites = ECache::get('post_favorites' . $post_id);
    if (false === $favorites) {
        $favorites = get_post_meta($post_id, 'favorite', true);
        if (!$favorites) {
            $favorites = 0;
        }
        ECache::set('post_favorites' . $post_id, EL_CACHE, DAY_IN_SECONDS);
    }
    // 获取存储已经点赞的文章ID列表的cookie
    $favorite_posts_cookie = isset($_COOKIE['favorited_posts']) ? $_COOKIE['favorited_posts'] : '';
    // 将cookie转换为数组
    $favorited_posts = explode(',', $favorite_posts_cookie);
    // 检查用户是否已经点赞了
    if (!in_array($post_id, $favorited_posts)) {
        wp_send_json_success(json_encode(
            array(
                'favorite' => $favorites,
                'pid' => $post_id,
                'isfavorited' => false,
                'msg' => '感谢您的收藏'
            )
        ));
    } else {
        wp_send_json_success(json_encode(
            array(
                'favorite' => $favorites,
                'pid' => $post_id,
                'isfavorited' => true,
                'msg' => '您已经收藏过了'
            )
        ));
    }
}

// Ajax请求文章列
// 处理Ajax加载更多文章请求
function load_more_posts()
{
    $page = $_POST['page'];

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'paged' => $page,
    );
    el_posts_list(array(), false, false);
    // $query = new WP_Query($args);

    // if ($query->have_posts()) {
    //     while ($query->have_posts()) {
    //         $query->the_post();
    //         // 输出文章内容，可以根据需要进行自定义
    //         el_posts_list();
    //     }
    // }
    wp_die();
}

add_action('wp_ajax_load_more_posts', 'load_more_posts');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');

/**
 * @description: 链接删除分页页码
 * @param {*} $url
 * @return {*}
 */
function el_url_del_paged($url)
{
    $url = remove_query_arg(array('paged'), $url);
    global $wp_rewrite;
    $url = preg_replace("/\/$wp_rewrite->pagination_base\/\d*/", "", $url);

    return $url;
}

/**
 * @description: 获取当前页面的链接函数
 * @param {*}
 * @return {*}
 */
function el_get_current_url()
{
    $home_url = home_url();
    $home_url = preg_replace('/^(http|https)(:\/\/)(?)([^\/]+).*$/im', '$1$2$3', $home_url);

    return $home_url . add_query_arg(null, false);
}

function el_ajax_order_post($query)
{
    $key = !empty($_REQUEST['key']) ? $_REQUEST['key'] : 'all';
    // $href   = add_query_arg($key, false, $uri);
    if ($query->is_main_query() && !is_admin() && $query->is_home()) {
        // Set parameters to modify the query
        $query->set('orderby', $key);
        $query->set('order', 'DESC');
        $query->set('suppress_filters', 'true');
    }
}
add_action('pre_get_posts', 'el_ajax_order_post');
add_action('wp_ajax_el_order_post', 'el_ajax_order_post');
add_action('wp_ajax_nopriv_el_order_post', 'el_ajax_order_post');


//function to modify default WordPress query
function wpb_custom_query($query)
{
    // Make sure we only modify the main query on the homepage 
    if ($query->is_main_query() && !is_admin() && $query->is_home()) {
        // Set parameters to modify the query
        $query->set('orderby', 'date');
        $query->set('order', 'DESC');
        $query->set('suppress_filters', 'true');
    }
}
// Hook our custom query function to the pre_get_posts
// add_action('pre_get_posts', 'wpb_custom_query');
